<?php
//公共
namespace newMobile\Controller;
use Think\Controller;
class CommonController extends Controller {
    
	function _initialize(){
        defined('TMPL_PATH') or define("TMPL_PATH", C("SP_TMPL_PATH"));
        $site_options=get_site_options();
        $this->assign($site_options);
     	$get_web_invoice=get_web_invoice();
      	$this->assign($get_web_invoice);
        //长时间登陆判断
    	if(isset($_COOKIE['user_id'])){
			//用cookie给session赋值
			$_SESSION['user_id']=$_COOKIE['user_id'];
			$_SESSION['user_name']=$_COOKIE['user_name'];
		}

        $the_host = $_SERVER['HTTP_HOST'];//取得当前域名
        $request_uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';//判断地址后面是否有参数
        if($the_host != 'm.58daiyan.com')//把这里的域名换上你想要的
        {
            header('HTTP/1.1 301 Moved Permanently');//发出301头部
            header('Location: https://m.58daiyan.com'.$request_uri);//跳转到你希望的地址格式
        }
        if(!isset($_SERVER['HTTPS'])){
            Header("HTTP/1.1 301 Moved Permanently");
            header('Location: https://m.58daiyan.com'.$_SERVER['REQUEST_URI']);
        }
        $citys=M('sys_city');
        $rs_citys=$citys->select();
        $city_settlesRes = array();
        foreach ($rs_citys as $k=>$v){
            $city_info['city_name']=$v['city_name'];
            $city_info['city_id']=$v['city_id'];
            $city_settlesRes[$v['header_code']][] =$city_info;//以这个首字母作为key
        }
        ksort($city_settlesRes);

        $this->assign('city_address',$city_address);
        $this->assign('city_settlesRes',$city_settlesRes);

		$store=M('store');
		$store_arr=$store
				->join('yt_sys_city on yt_sys_city.city_id=yt_store.city')
				->field('yt_store.city,yt_sys_city.city_name ')
				->where('yt_store.status=1')
				->group('yt_store.city')
				->select();
		if(cookie('site_city')==null||cookie('site_city_id')==null){
			if($store_arr){
				cookie('site_city',$store_arr[0]['city_name'],604800);
				cookie('site_city_id',$store_arr[0]['city'],604800);
			}
		}
		 $this->assign('store_arr',$store_arr);
		 $isweixin=is_weixin();

		 $weixin_action=array('weixinbd');
		 $weixin_name=ACTION_NAME;
		
		//自动获取微信用户信息 未登陆  未主动退出
		if($isweixin&&session('user_id')==null&&$zd_out!=1&&session('openid')==null&&session('unionid')==null){
			$appid=C('weixin.APP_KEY');
			$url=get_url();
			if($_GET["code"]){    
              
				$appsecret=C('weixin.APP_SECRET');
				$code=$_GET["code"];
				$rs=get_weixin_info($appid,$appsecret,$code);
            
				$is_fllow=is_fllow($rs['openid']);
				if($is_fllow['subscribe']==0){
					$is_fllow=get_weixin_user_info($rs['access_token'],$rs['openid']);
					$is_fllow['subscribe']=0;
				}
				session('openid',$rs['openid']);
				session('unionid',$is_fllow['unionid']);
				$is_fllow=json_encode($is_fllow);
				session('weixin_info',$is_fllow);
			}else{
               get_access_token($appid,$url);
			}
		}
      
      if($isweixin&&session('user_id')){
         $uid=session('user_id');
         $user_info=M('users')->find($uid);
          if($user_info['wx_h5openid']==null){
                 $appid=C('weixin.APP_KEY');
                 $appsecret=C('weixin.APP_SECRET');
                 $url=get_url();
                 if($_GET["code"]){
                    $code=$_GET["code"];
                    $rs=get_weixin_info($appid,$appsecret,$code);
                    $h5_info['id']=$uid;                   
                    $h5_info['wx_h5openid']=$rs['openid'];
					M('users')->save($h5_info);                   
                 }else{
                    get_access_token($appid,$url,'snsapi_userinfo');
                 }
          }
       
         
      
      }
     
		if($isweixin&&session('openid')){
			$weixin_info=session('weixin_info');
			$weixin_info=json_decode($weixin_info,true);
			
			$openid=session('openid');
			$unionid=session('unionid');
			
			
			if($unionid){
				//记录日志
				$weixin_log=M('weixin')->where("unionid='".$unionid."'")->find();
				
				if(!$weixin_log){
					$data['opend_id']=$weixin_info['openid'];
					$data['unionid']=$weixin_info['unionid'];
					$data['nickname']=$weixin_info['nickname'];
					$data['sex']=$weixin_info['sex'];
					$data['city']=$weixin_info['city'];
					$data['country']=$weixin_info['country'];
					$data['province']=$weixin_info['province'];
					$data['headimgurl']=$weixin_info['headimgurl'];
					$data['subscribe_time']=$weixin_info['subscribe_time'];
					$data['subscribe']=$weixin_info['subscribe'];
					if($data['nickname']){
						M('weixin')->add($data);
					}
				}
			}
		
			
			if(session('user_id')){
				//已登陆
				$is_bd=M('users')->where("wx_unionid='".$weixin_info['unionid']."'")->find();
				if($is_bd==null){
					$uid=session('user_id');
					$user_w=M('users')->find($uid);
					if($user_w['is_jiebd']==0){
						//第一次自动绑定
						if($user_w['openid']==null||$user_w['openid']==''||$user_w['wx_is_sub']!=$weixin_info['subscribe']){
							$user_info['wx_openid']=$weixin_info['openid'];
							$user_info['wx_unionid']=$weixin_info['unionid'];
							$user_info['wx_is_sub']=$weixin_info['subscribe'];
							$user_info['wx_name']=$weixin_info['nickname'];
							$user_info['id']=session('user_id');
							M('users')->save($user_info);
						}
					}
					
				}
				
			}else{
				$youke_info=M('users')->where("wx_unionid='".$weixin_info['unionid']."'")->find();
				//未登陆
				$zd_out=session('zd_out');
				if($youke_info&&$zd_out!=1){
					//存在自动登陆,不是主动注销
					if($youke_info['wx_openid']==null){
						$user_info['id']=$youke_info['id'];
						$user_info['wx_openid']=$weixin_info['openid'];
						M('users')->save($user_info);
					}
					session('user_id',$youke_info['id']);
				}elseif($zd_out!=1){
					//不存在创建游客账号,不是主动注销
					$controller=CONTROLLER_NAME;
					$action=ACTION_NAME;
					if($controller=='Index'&&$action=='tj_user'){
						$youke['tj_userid']=I('get.id');
					}
					$youke['username']=$weixin_info['nickname'];
					$youke['password']="8888888";
					$youke['wx_name']=$weixin_info['nickname'];
					$youke['ishidden']=1;
					$youke['addtime']=time();
					$youke['user_pic']=$weixin_info['headimgurl'];
					$youke['login_time']=date('Y-m-d H:i:s',time());
					$youke['sex']=$weixin_info['sex'];
					$youke['wx_openid']=$weixin_info['openid'];
					$youke['wx_unionid']=$weixin_info['unionid'];
					$youke['wx_is_sub']=$weixin_info['subscribe'];
					$youke['type']=1;
					$youke_id=M('users')->add($youke);
					session('user_id',$youke_id);
				}
				
				
			}
		}
		 
		
		
	}
	
	
	
	public function ajax_r($code='0',$data='',$message='') {
		$msg['code']=$code;
		$msg['data']=$data;
		$msg['message']=$message;
	 	$this->ajaxReturn($msg);
	}
    //处理所有没有的方法的处理方法，引导到404页面
    public function _empty() {
        R('Empty/_empty');
    }
    /**
     * 加载模板和页面输出 可以返回输出内容
     * @access public
     * @param string $templateFile 模板文件名
     * @param string $charset 模板输出字符集
     * @param string $contentType 输出类型
     * @param string $content 模板输出内容
     * @return mixed
     */
    public function display($templateFile = '', $charset = '', $contentType = '', $content = '', $prefix = '') {
        parent::display($this->parseTemplate($templateFile), $charset, $contentType,$content,$prefix);
    }

    /**
     * 获取输出页面内容
     * 调用内置的模板引擎fetch方法，
     * @access protected
     * @param string $templateFile 指定要调用的模板文件
     * 默认为空 由系统自动定位模板文件
     * @param string $content 模板输出内容
     * @param string $prefix 模板缓存前缀*
     * @return string
     */
    public function fetch($templateFile='',$content='',$prefix=''){
        $templateFile = empty($content)?$this->parseTemplate($templateFile):'';
        return parent::fetch($templateFile,$content,$prefix);
    }
    
    /**
     * 自动定位模板文件
     * @access protected
     * @param string $template 模板文件规则
     * @return string
     */
    public function parseTemplate($template='') {
        
        $tmpl_path=C("SP_TMPL_PATH");
        define("SP_TMPL_PATH", $tmpl_path);
        if($this->theme) { // 指定模板主题
            $theme = $this->theme;
        }else{
            // 获取当前主题名称
            $theme      =    C('SP_DEFAULT_THEME_MOBLIE');
            if(C('TMPL_DETECT_THEME')) {// 自动侦测模板主题
                $t = C('VAR_TEMPLATE');
                if (isset($_GET[$t])){
                    $theme = $_GET[$t];
                }elseif(cookie('think_template_moblie')){
                    $theme = cookie('think_template_moblie');
                }
                if(!file_exists($tmpl_path."/".$theme)){
                    $theme  =   C('SP_DEFAULT_THEME_MOBLIE');
                }
                cookie('think_template_moblie',$theme,864000);
            }
        }
        
        $theme_suffix="";
        
        if(C('MOBILE_TPL_ENABLED') && sp_is_mobile()){//开启手机模板支持
            
            if (C('LANG_SWITCH_ON',null,false)){
                if(file_exists($tmpl_path."/".$theme."_mobile_".LANG_SET)){//优先级最高
                    $theme_suffix  =  "_mobile_".LANG_SET;
                }elseif (file_exists($tmpl_path."/".$theme."_mobile")){
                    $theme_suffix  =  "_mobile";
                }elseif (file_exists($tmpl_path."/".$theme."_".LANG_SET)){
                    $theme_suffix  =  "_".LANG_SET;
                }
            }else{
                if(file_exists($tmpl_path."/".$theme."_mobile")){
                    $theme_suffix  =  "_mobile";
                }
            }
        }else{
            $lang_suffix="_".LANG_SET;
            if (C('LANG_SWITCH_ON',null,false) && file_exists($tmpl_path."/".$theme.$lang_suffix)){
                $theme_suffix = $lang_suffix;
            }
        }
        
        $theme=$theme.$theme_suffix;
        
        C('SP_DEFAULT_THEME_MOBLIE',$theme);
        
        $current_tmpl_path=$tmpl_path.$theme."/";
        // 获取当前主题的模版路径
        define('THEME_PATH', $current_tmpl_path);
        
        C("TMPL_PARSE_STRING.__TMPL__",__ROOT__."/".$current_tmpl_path);
        
        
        C('SP_VIEW_PATH',$tmpl_path);
        C('DEFAULT_THEME',$theme);
        
        define("SP_CURRENT_THEME", $theme);
        
        if(is_file($template)) {
            return $template;
        }
        $depr       =   C('TMPL_FILE_DEPR');
        $template   =   str_replace(':', $depr, $template);
        
        // 获取当前模块
        $module   =  MODULE_NAME;
        if(strpos($template,'@')){ // 跨模块调用模版文件
            list($module,$template)  =   explode('@',$template);
        }
        
        $module =$module."/";
        
        // 分析模板文件规则
        if('' == $template) {
            // 如果模板文件名为空 按照默认规则定位
            $template = CONTROLLER_NAME . $depr . ACTION_NAME;
        }elseif(false === strpos($template, '/')){
            $template = CONTROLLER_NAME . $depr . $template;
        }
        
        $file = sp_add_template_file_suffix($current_tmpl_path.$module.$template);
        $file= str_replace("//",'/',$file);
        if(!file_exists_case($file)) E(L('_TEMPLATE_NOT_EXIST_').':'.$file);
        return $file;
    }

}
?>
